package com.tuanzi.loan.web.bean.xhh.settlementsystem;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.starbaba.model.utils.JSONUtils;
import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.system.SystemUser;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementBill;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementCompany;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementPrepay;
import com.tuanzi.loan.business.service.xhh.settlementsystem.*;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.xhh.settlementsystem.XhhSettlementPrepayRequest;
import com.tuanzi.loan.vo.response.xhh.settlementsystem.XhhSettlementPrepayResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.xhh.settlementsystem.XhhSettlementPrepayLazyDataModel;
import com.tuanzi.loan.workflow.service.WorkflowManagerService;
import com.tuanzi.loan.workflow.service.WorkflowProcessorService;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @author caiwanlin
 * @create 2018-08-22 17:48
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class XhhSettlementPrepayListBean extends JSFListingBean<XhhSettlementPrepayRequest, XhhSettlementPrepayResponse> {
	@Autowired
	private XhhSettlementCompanyService xhhSettlementCompanyService;

	@Autowired
	private XhhSettlementPrepayService xhhSettlementPrepayService;

	@Autowired
	private XhhSettlementBillService xhhSettlementBillService;

	@Autowired
	private WorkflowManagerService workflowManagerService;

	@Autowired
	private WorkflowProcessorService workflowProcessorService;

	private List<XhhSettlementCompany> companyList;

	private List<XhhSettlementPrepayResponse> selectPrepayList;

	private XhhSettlementPrepay settlementPrepay;

	private XhhSettlementBill settlementBill;// 开票

	private List<SystemUser> checkList;// 财务核查人

	private String PROCESS_DEF_KEY = "XhhBillSystem";// 流程定义key

	private Double toTalOrderCount = 0.00D;

	private Double aliOrderCount = 0.00D;

	private Double bankOrderCount = 0.00D;

	private Double wechatOrderCount = 0.00D;

	@PostConstruct
	public void init() throws Exception {
		companyList = xhhSettlementCompanyService.getCompanyList();
		settlementPrepay = new XhhSettlementPrepay();
		settlementBill = new XhhSettlementBill();
		initLazyDataModel();
	}

	private void initLazyDataModel() throws Exception {
		$ = new XhhSettlementPrepayRequest();
		lazyDataModel = new XhhSettlementPrepayLazyDataModel($);
	}

	public void onReset() throws Exception {
		initLazyDataModel();
	}

	public void onAdd() {
		settlementPrepay = new XhhSettlementPrepay();
	}

	public void onDelete(Long id, Integer billStatus) {
		if (null == billStatus || !billStatus.equals(0)) {
			addErrorMessage("不能删除已开票的记录");
			return;
		}
		XhhSettlementPrepay one = xhhSettlementPrepayService.findOne(id);
		if ("1".equals(one.getPrepayStatus())) {
			addErrorMessage("不能删除已核对的记录");
			return;
		}
		xhhSettlementPrepayService.onDelete(id);
		addSuccessfullyMessage();
	}
	public void count (){
		toTalOrderCount = xhhSettlementPrepayService.getToTalOrderCount($);
		aliOrderCount = xhhSettlementPrepayService.getAliOrderCount($);
		bankOrderCount = xhhSettlementPrepayService.getBankOrderCount($);
		wechatOrderCount = xhhSettlementPrepayService.getWechatOrderCount($);
	}

	public void onStatus(Long id) {
		XhhSettlementPrepay one = xhhSettlementPrepayService.findOne(id);
		if (one.getPrepayStatus() != null && one.getPrepayStatus().equals(1)) {
			addWarnMessage("已经核对");
			return;
		}
		one.setPrepayStatus(1);
		xhhSettlementPrepayService.saveOrUpdate(one);

	}

	public void onSee(Long id) {
		settlementPrepay = xhhSettlementPrepayService.findOne(id);
	}

	public void onSave() {
		if (!validate())
			return;
		if (Boolean.TRUE.equals(settlementPrepay.getPrepayStatus())) {
			addErrorMessage("不能更改已核对的记录");
			return;
		}
		// 获取公司名称
		// String companyName = companyList.parallelStream().filter(c -> {
		// if (c.getId() == settlementPrepay.getCompanyId()) return true;
		// return false;
		// }).map(s -> s.getCompanyName()).findFirst().get();
		XhhSettlementCompany con = xhhSettlementCompanyService.findOne(settlementPrepay.getCompanyId());
		if (con == null) {
			addErrorMessage("查询不到公司");
			return;
		}
		String companyName = con.getCompanyName();
		settlementPrepay.setCompanyName(companyName);
		xhhSettlementPrepayService.onSave(settlementPrepay);
		execute("PF('adding').hide();");
		update("prepayForm");
	}

	public void onBill() {
		// 是否选择预付记录
		if (selectPrepayList == null || selectPrepayList.isEmpty()) {
			addErrorMessage("请选择预付记录");
			return;
		}
		// 判断是否选的是未开票的记录
		long count = selectPrepayList.parallelStream().filter(s -> !s.getBillStatus().equals(XhhBillStatus.NO_BILL.index)).count();
		if (count > 0) {
			addErrorMessage("请选择未开票的记录");
			return;
		}
		// 判断是否选择同一主体开票
		Map<Long, List<XhhSettlementPrepayResponse>> collect = selectPrepayList.parallelStream().collect(Collectors.groupingBy(XhhSettlementPrepayResponse::getCompanyId));
		if (collect.size() > 1) {
			addErrorMessage("请选择同一个主体开票");
			return;
		}

		//
		// 查询主体
		XhhSettlementPrepayResponse settlementPrepayResponse = selectPrepayList.get(0);
		XhhSettlementCompany settlementCompany = xhhSettlementCompanyService.findOne(settlementPrepayResponse.getCompanyId());
		// 开票金额
		Double prepayAmount = selectPrepayList.parallelStream().map(s -> s.getPrepayAmount()).collect(Collectors.summingDouble(s -> s));
		settlementBill = xhhSettlementBillService.structureSettlementBill(settlementCompany);
		settlementBill.setBillAmount(prepayAmount);
		// 记录类型(预付)
		settlementBill.setRecordType(XhhRemainType.PREPAY.index);

		checkList = workflowManagerService.findFirstActivitySystemUserProcDefKey(PROCESS_DEF_KEY);
		execute("PF('billing').show();");
		update("prepayForm:bill-dialog");
	}

	public void onSaveBill() {
		String result = xhhSettlementBillService.validateBill(settlementBill);
		if (StringUtils.isNotBlank(result)) {
			addErrorMessage(result);
			return;
		}
		// 保存
		String checkName = checkList.parallelStream().filter(s -> s.getAccount().equals(settlementBill.getCheckAccount())).map(s -> s.getName()).findFirst().get();
		settlementBill.setCheckName(checkName);// 审核人姓名
		List<Long> ids = selectPrepayList.parallelStream().map(s -> (Long) s.getId()).collect(Collectors.toList());
		settlementBill.setDetailList(JSONUtils.toJsonString(selectPrepayList));// 保存此时刻明细快照
		xhhSettlementBillService.onSave(settlementBill, ids);
		selectPrepayList = Lists.newArrayList();

		// 启动流程
		String account = CurrentUser.get().getAccount();
		String assignee = settlementBill.getCheckAccount();
		String title = "(熊花花)【" + settlementBill.getCompanyName() + "】预付开票流程";
		List<String> businessKeys = Lists.newArrayList(settlementBill.getId().toString());
		Map<String, Object> variables = Maps.newHashMap();
		workflowProcessorService.startProcess(account, assignee, PROCESS_DEF_KEY, title, businessKeys, variables);

		addSuccessfullyMessage();
		execute("PF('billing').hide();");
		update("prepayForm");
	}

	public boolean validate() {
		if (settlementPrepay.getCompanyId() == null) {
			addErrorMessage("没有选择主体");
			return false;
		}
		if (settlementPrepay.getPrepayTime() == null) {
			addErrorMessage("没有选择充值日期");
			return false;
		}
		if (settlementPrepay.getPrepayAmount() == null) {
			addErrorMessage("充值金额为空");
			return false;
		}
		if (settlementPrepay.getPayMode() == null) {
			addErrorMessage("没有选择付款方式");
			return false;
		}
		if (settlementPrepay.getPayName() == null) {
			addErrorMessage("支付账户为空");
			return false;
		}
		if (settlementPrepay.getPayAccount() == null) {
			addErrorMessage("支付账号为空");
			return false;
		}
		if (Boolean.TRUE.equals(settlementPrepay.getPrepayStatus())) {
			addErrorMessage("不能删除已核对的记录");
			return false;
		}
		return true;
	}

	public void onUploadAttachment(FileUploadEvent event) {
		settlementBill.setAttachmentUrl(this.uploadImg(event.getFile()));
		addInfoMessage("上传成功");

	}

	public void onUploadImgAttachment(FileUploadEvent event) {
		settlementBill.setImgAttachmentUrl(this.uploadImg(event.getFile()));
		addInfoMessage("上传成功");

	}

	public void onDeleteAttachment(String type) {
		if (StringUtils.isBlank(type)) {
			settlementBill.setAttachmentUrl(null);
		} else {
			settlementBill.setImgAttachmentUrl(null);
		}
		addInfoMessage("删除成功");
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(XHH_SETTLEMENT_PAY_MODE, XHH_SETTLEMENT_BILLING_CONTENT, XHH_SETTLEMENT_BILL_TYPE);
	}
}
